#include "stdafx.h"
#include "OrderLinkFactory.h"

#include "config.h"
#include "LogFile.h"


// supported order link
// Ctp

#include "CtpOrderLink.h"

static CtpOrderLink* CreateCtpOrderLink() {
	LogFile::PrintLine("Creating CTP order link now");
	Config *cfg = Config::getInstance();

	string tradeApiUrl;
	if(!cfg->getValue("TradeApiUrl", &tradeApiUrl)) {
		LogFile::PrintLine("Cannot find trader api url", false);
		return 0;
	}
	char addr[512];
	sprintf(addr, "%s", tradeApiUrl.c_str());

	CThostFtdcTraderApi *api = 
		CThostFtdcTraderApi::CreateFtdcTraderApi(cfg->getValue("TradeApiPath", "zzTradeApi.con").c_str());

	CtpOrderLink *orderLink = new CtpOrderLink( "order", api );
	orderLink->loadSettings();

	api->RegisterSpi ( orderLink );
	api->SubscribePrivateTopic(THOST_TERT_RESUME);
	api->SubscribePublicTopic(THOST_TERT_RESUME);
	api->RegisterFront( addr );

	LogFile::PrintLine("CTP order link created now", false);
	
	return orderLink;
}



OrderLinkFactory* OrderLinkFactory::Instance = 0;

OrderLinkFactory::OrderLinkFactory() {
}


OrderLinkFactory::~OrderLinkFactory() {
}


void OrderLinkFactory::Create() {
	if(Instance == 0) {
		Instance = new OrderLinkFactory();
	}
}

OrderLink* OrderLinkFactory::GetLink() {
	Config *cfg = Config::getInstance();
	string linkType = cfg->getValue("OrderLinkType", "");
	if(linkType == "ctp") {
		return CreateCtpOrderLink();
	} else {
		return 0;
	}
}